﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "CmdFinishDrawFloorProfile.h"
#include "GbmpBuiltInCategoryUniIdentitiesNew.h"
#include "StructureInstancePresetParameterUtils.h"
#include "StructureInstanceCmdUtils.h"
#include "StructureEditProfileUtils.h"
#include "StructureProfileInstanceInput.h"
#include "IStructureFloor.h"
#include "ProfileUsedModelLineUtils.h"
#include "StructureFloorUtils.h"
#include "GmUiStructureCommandRegister.h"
#include "StructureCmdIds.h"

#include "IDocument.h"
#include "IPlane.h"
#include "IUserTransaction.h"
#include "IStructureSlopeLine.h"
#include "IEditMode.h"
#include "StructureEditModeTypes.h"
#include "IStructureFloorEditModeBehavior.h"
#include "IModelView.h"
#include "UiCommonDialog.h"
#include "IModelLine.h"
#include "ISelection.h"
#include "IInstance.h"
#include "IUiDocument.h"
#include "UserTransactionGroupUtils.h"
#include "CmdStatusUtils.h"
#include "IParameterDefinitionLibrary.h"
#include "IGenericElement.h"
#include "IElementStatus.h"
#include "IHighlights.h"
#include "GbmpDocUtils.h"
#include "UiDocumentViewUtils.h"

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

REGISTER_GM_COMMAND(CmdFinishDrawFloorProfile)

//////////////////////////////////////////////////////////////////
//CmdFinishDrawProfile
CmdFinishDrawFloorProfile::CmdFinishDrawFloorProfile(const std::wstring& cmdId /*= ID_CMD_STRUCTURE_FINISH_DRAW_PROFILE*/)
    :GbmpCommandBase(ID_CMD_EDIT_STRUCTURE_FLOOR_FINISH)
{

}

bool CmdFinishDrawFloorProfile::IsEnabled() const
{
    if (!CommandBase::IsEnabled())
        return false;

    CMD_ONLY_ENABLE_IN_PROJECT_ENVIRONMENT
}

bool CmdFinishDrawFloorProfile::IsVisible() const
{
    CMD_ONLY_VISIBLE_IN_PROJECT_ENVIRONMENT
}

OwnerPtr<IAction> CmdFinishDrawFloorProfile::ExecuteCommand(const CommandParameters& cmdParams)
{
    IDocument* pDoc = UiDocumentViewUtils::GetCurrentDocument();
    DBG_WARN_AND_RETURN_UNLESS(pDoc, nullptr, L"没有当前文档",L"GDMPLab",L"2024-03-30");

    IModelView* pModelView = UiDocumentViewUtils::GetCurrentModelView();
    DBG_WARN_AND_RETURN_UNLESS(pModelView, nullptr, L"没有当前视图",L"GDMPLab",L"2024-03-30");

    const IEditMode* pProfileEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::StructureFloorEditModeType);
    DBG_WARN_AND_RETURN_UNLESS(pProfileEditMode, nullptr, L"获取当前编辑模式失败！",L"GDMPLab",L"2024-03-30");

    const IStructureFloorEditModeBehavior* pProfileEDBehavior = quick_cast<const IStructureFloorEditModeBehavior>(pProfileEditMode->GetEditModeBehavior());
    DBG_WARN_AND_RETURN_UNLESS(pProfileEDBehavior, nullptr, L"pProfileEDBehavior为空！",L"GDMPLab",L"2024-03-30");

    bool bIsCreating = pProfileEditMode->GetIsCreating();
    ElementId familyId = pProfileEDBehavior->GetEditingFamilyId();
    ElementId instanceTypeId = pProfileEDBehavior->GetEditingInstanceTypeId();

    std::vector<IModelLine*> profileCurves;
    ProfileUsedModelLineUtils::GetStructureProfileModelLinesInCurrDoc(pDoc, profileCurves);

    if (profileCurves.empty())
    {
        UiCommonDialog::ShowMessageBox(GBMP_TR(L"警告"), GBMP_TR(L"轮廓为空，无法完成绘制轮廓！"), (int)UiCommonDialog::ButtonType::OK);
        return nullptr;
    }
    OwnerPtr<IPlane> opWorkPlane = pModelView->GetWorkPlane();

    //计算坡度线
    IStructureSlopeLine* pSlopeLine = nullptr;
    {
        std::vector<const IStructureSlopeLine*> slopLines;
        std::vector<IElement*> allSlopElements = gcmp::GbmpDocUtils::GetElementsByCategory(pDoc, BuiltInCategoryUniIdentities::BICU_STRUCTURE_SLOPELINE);
        FOR_EACH(pElement, allSlopElements)
        {
            IGenericElement* pGenericElem = quick_cast<IGenericElement>(pElement);
            DBG_WARN_AND_CONTINUE_UNLESS(pGenericElem, L"pGenericElem为空！",L"GDMPLab",L"2024-03-30");

            IStructureSlopeLine* pSlope = quick_cast<IStructureSlopeLine>(pGenericElem->GetExternalObject());
            if (pSlope && ((const IGenericElement*)pGenericElem)->GetStatus()->IsVisible())
            {
                slopLines.push_back(pSlope);
                pSlopeLine = pSlope;
            }
        }
        if (slopLines.size() > 1)
        {
            UiCommonDialog::ShowMessageBox(GBMP_TR(L"警告"), GBMP_TR(L"不支持绘制多条坡度线。"), (int)UiCommonDialog::ButtonType::OK);
            return nullptr;
        }
    }

    if (!StructureEditProfileUtils::CheckForValidLoops(profileCurves, opWorkPlane->GetCoordinate(), false, true))
        return nullptr;

    if (bIsCreating)
    {
        const IInstance* pPresetInstance = dynamic_cast<const IInstance*>(UiDocumentViewUtils::GetCurrentDocument()->GetElement(pProfileEDBehavior->GetPresetElementId()));
        DBG_WARN_AND_RETURN_UNLESS(pPresetInstance, nullptr, L"pPresetInstance为空！",L"GDMPLab",L"2024-03-30");
        if (!ValidateCompensationThickness(pPresetInstance, profileCurves, pSlopeLine))
        {
            UserTransactionGroupUtils::CommitLatestActive(pDoc);
            return nullptr;
        }

        OwnerPtr<StructureProfileInstanceElementInput> opInput = NEW_AS_OWNER_PTR(StructureProfileInstanceElementInput);
        bool bOk = StructureInstanceCmdUtils::GenerateStructurePlateInput(pDoc, pModelView, GetCategory(), GetCategorySecondKey(), familyId, instanceTypeId, *opInput);
        DBG_WARN_AND_RETURN_UNLESS(bOk, nullptr, L"pInput生成失败！",L"GDMPLab",L"2024-03-30");
        opInput->ProfileCurves = profileCurves;
        opInput->FloorSlopeLine = pSlopeLine;

        OwnerPtr<IUserTransaction> ut = IUserTransaction::Create(pDoc, GBMP_TR(L"完成编辑轮廓实例"));
        // 退出编辑模式，确保Instance Calculators可以开始工作
        IEditMode* pEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::StructureFloorEditModeType);
        DBG_WARN_AND_RETURN_UNLESS(pEditMode, nullptr, L"获取当前编辑模式失败！",L"GDMPLab",L"2024-03-30");
        pEditMode->EndEditing(pDoc);

        IStructureFloor* pStructureFloor = IStructureFloor::Create(opInput.get());
        DBG_WARN_AND_RETURN_UNLESS(pStructureFloor, nullptr, L"结构楼板创建失败",L"GDMPLab",L"2024-03-30");

        ut->Commit();
    }
    else
    {
        ElementId idInstance = pProfileEditMode->GetEditingElementId();
        const IInstance *pInstance = quick_cast<IInstance>(pDoc->GetElement(idInstance));
        if (!ValidateCompensationThickness(pInstance, profileCurves, pSlopeLine)) {
            UserTransactionGroupUtils::CommitLatestActive(pDoc);
            return nullptr;
        }

        OwnerPtr<StructureProfileInstanceEditElementInput> opInput = NEW_AS_OWNER_PTR(StructureProfileInstanceEditElementInput);
        opInput->Document = pDoc;
        opInput->InstanceId = idInstance;
        opInput->FloorSlopeLine = pSlopeLine;
        opInput->ProfileCurves = profileCurves;

        OwnerPtr<IUserTransaction> ut = IUserTransaction::Create(pDoc, GBMP_TR(L"完成编辑轮廓实例"));
        {
            IEditMode* pEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::StructureFloorEditModeType);
            DBG_WARN_AND_RETURN_UNLESS(pEditMode, nullptr, L"获取当前编辑模式失败！",L"GDMPLab",L"2024-03-30");

            // 退出编辑模式，确保Instance Calculators可以开始工作
            pEditMode->EndEditing(pDoc);
            IStructureFloor* pFloor = IStructureFloor::Edit(opInput.get());
            if (!pFloor)
            {
                ut->Rollback();
                UserTransactionGroupUtils::CommitLatestActive(pDoc);
                return nullptr;
            }
            ISelection::Get()->Clear(pDoc);
            IHighlights::Get()->Clear();
        }
        ut->Commit();
    }
    UserTransactionGroupUtils::CommitLatestActive(pDoc);
    UiDocumentViewUtils::GetCurrentUiDocument()->UpdateView();
    return nullptr;
}

Int32 gcmp::CmdFinishDrawFloorProfile::GetCategorySecondKey() const
{
    return 0;
}

UniIdentity gcmp::CmdFinishDrawFloorProfile::GetCategory() const
{
    UniIdentity categoryUid = BuiltInCategoryUniIdentities::BICU_STRUCTURE_FLOOR;
    return categoryUid;
}

bool gcmp::CmdFinishDrawFloorProfile::ValidateCompensationThickness(const IInstance* pInstance, const std::vector<IModelLine*>& profileCurves, const IStructureSlopeLine* pSlopeLine)
{
    double compensationThickNess = 0.0;
    bool isOk = StructureFloorUtils::CalculateFloorScratchHeight(pInstance, profileCurves, pSlopeLine, compensationThickNess);
    {
        //****************************************需要注意**************************************************
        //为什么Constants::MAX_MODEL_SIZE / 3.0，为了与 AlgorithmBodyTopologyOperate::FitBodyToTargetedFaceWithoutTopoChange的延伸值一直
        if (!isOk || compensationThickNess > Constants::MAX_MODEL_SIZE / 3.0)
        {
            UiCommonDialog::ShowMessageBox(GBMP_TR(L"警告"), GBMP_TR(L"坡度线离板轮廓太远或者板轮廓太大！"), (int)UiCommonDialog::ButtonType::OK);
            return false;
        }
    }
    return true;
}

